// src/utils/versionChecker.js
const CHECK_INTERVAL = 5 * 60 * 1000; // 5分钟检查一次
const VERSION_KEY = "app_version";
import { message } from "ant-design-vue";

export function initVersionCheck() {
  // 立即检查
  checkVersion();

  // 定时检查
  setInterval(checkVersion, CHECK_INTERVAL);

  // 网络恢复时检查
  window.addEventListener("online", checkVersion);
}

async function checkVersion() {
  try {
    const res = await fetch("/version.json?t=" + Date.now(), {
      cache: "no-store",
    });

    if (!res.ok) return;

    const { version } = await res.json();
    console.log(version, "===26");
    const currentVersion = localStorage.getItem(VERSION_KEY);

    if (!currentVersion) {
      // 首次访问
      localStorage.setItem(VERSION_KEY, version);
    } else if (version !== currentVersion) {
      // 版本不一致
      showUpdateNotification();
    }
  } catch (err) {
    console.error("Version check failed:", err);
  }
}

function showUpdateNotification() {
  message.success("需要更新了");
  // 事件监听
  // notice.querySelector(".refresh-btn").onclick = () => {
  //   localStorage.setItem(VERSION_KEY, version);
  //   window.location.reload();
  // };

  // notice.querySelector(".later-btn").onclick = () => {
  //   notice.remove();
  // };

  // 10秒后自动消失
  // setTimeout(() => notice.remove(), 10000);
}
